<template>
  <div class="groupNameDetail" id="groupNameDetail">
    <!-- 功能按钮 -->
    <div class="groupNameDetail_button">
      <a-button class="addButton" type="primary" 
      :disabled="!btnPerm.includes('creatAble')" @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        添加
      </a-button>
      <div class="statusSelect">
        状态：
        <a-select v-model:value="statusType" @change="statusChange" :options="statusOptions"></a-select>
      </div>
      <div class="searchContent">
        <a-input v-model:value="groupNameDetail" placeholder="搜索用户名、手机号、邮箱号" style="width: 232px" @blur="onSearch">

        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <div class="groupName">
      会员组名称：<span>{{ groupName }}</span>
    </div>

    <baseTable :columns="columns.memberGroupDetailColumn" :dataSource="configData.records" :isSelect="true"
      :scroll="scroll" ref="hotBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @deleteRecord="deleteSelectedAll" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'isEnabled'">
          <a-switch @click="switchChange(record)" size="small" v-model:checked="record.isEnabled" :disabled='isPrevent' />
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('detailAble') }" @click="showDetail(record)">{{
            record.oparation[0]
          }}</a>

          <a-popconfirm :disabled="!btnPerm.includes('deleteAble')" v-if="query.isDefault == '0'" placement="topRight" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                该会员移除后将被移动到默认分组
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ record.oparation[1] }}</a>
          </a-popconfirm>
          <a class="eidtRecords1"
          :class="{ disable: !btnPerm.includes('moveAble')}"
           @click="moveMember(record)">{{
            record.oparation[2]
          }}</a>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length">启用</a-button>
        <a-button :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length">禁用</a-button>
        <a-button v-if="query.isDefault == '0'" :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length ||!btnPerm.includes('deleteAble') ">移除</a-button>
        <a-button :style="{ 'margin-left': '8px' }" @click="moveMember('allmove')"
          :disabled="!rowSelection.length || !btnPerm.includes('moveAble')">移动</a-button>
      </template>
    </baseTable>

    <!-- 添加会员模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false">
      <template v-slot:body>
        <template v-if="isAdd">
          <div class="add-item">
            <div class="header-content">
              <div class="group-select">
                所属分组：
                <a-select v-model:value="moveValue" placeholder="筛选分组" :options="moveOptions"
                  @change="selectGroup"></a-select>
              </div>
              <div class="searchContent">
                <a-input v-model:value="groupNameDetail" placeholder="搜索会员名、手机号、邮箱号" style="width: 192px">
                  <template #suffix>
                    <i class="iconfont icon-search" @click="onSearch"></i>
                  </template>
                </a-input>
              </div>
            </div>
            <div class="baseTable">
              <baseTable :columns="columns.memberGroupDetailaddColumn" :dataSource="configData1.records" :isSelect="true"
                :scroll="{ y: 260 }" ref="addNewTables" :isShowPagination="isShowPagination"
                :showCheckDelete="showCheckDelete" :total="configData1.total" @deleteRecord="deleteSelectedAll"
                @changePage="changePage_motal">
                <template #bodyCell="{ column, text, record }">
                  <template v-if="column.ellipsis">
                    <table-tool-tip :text="text" :column="column"></table-tool-tip>
                  </template>
                  <template v-if="column.dataIndex === 'isEnabled'">
                    <a-switch @click="switchChange(record)" size="small" v-model:checked="record.isEnabled"
                      :disabled='isPrevent' />
                  </template>
                  <template v-if="column.dataIndex === 'oparation'">
                    <a class="eidtRecords" @click="showDetail(record)">{{
                      record.oparation[0]
                    }}</a>

                    <a-popconfirm v-if="query.isDefault == '0'" placement="topRight" @confirm="confirmDelete(record)">
                      <template #title>
                        <p style="width: 197px">
                          该会员移除后将被移动到默认分组
                        </p>
                      </template>
                      <a>{{ record.oparation[1] }}</a>
                    </a-popconfirm>
                    <a class="eidtRecords1" @click="moveMember(record)">{{
                      record.oparation[2]
                    }}</a>
                  </template>
                </template>
              </baseTable>
            </div>
          </div>
        </template>
        <template v-if="isMove">
          <div class="move-item">
            <span>将所选会员移动到其他分组</span>
            <div class="memberList">
              <span>会员：</span> <span v-for="(item, index) in memberList" :key="index">{{ item }} ; </span>
            </div>
            <a-select v-model:value="moveValue" placeholder="请选择移动后的分组" :options="moveOptions"
              @change="selectMove"></a-select>
          </div>
        </template>
      </template>
    </base-modal>


    <!-- 会员详情-->
    <base-modal :width="modAlProps.width" :isVisible="isVisibleDetail" :title="modAlProps.title" :buttons="[]"
      cancleText="关闭" @handleOk="buttonMessage" @handleCancle="isVisibleDetail = false" class="member_detail_modal">
      <template v-slot:body>
        <a-form name="advanced_search" autoComplete="off" :model="memberFormState" ref="member_REF">
          <template v-for="(item, index) in memberFormState">
            <div class="basic-item">
              <component :is="comps[item.componentName]" :formNamePath="[index, 'value']" :index="index" :element="item"
                v-if="item" />
            </div>
          </template>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode, watch } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { useRoute } from "vue-router";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import { comps } from '@/components/draggable/exportComp'
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal"
import upload from "@/components/upload/uploadFile.vue"
import { checkGroupName } from "./formRuler";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { encrypt3DES, decrypt3DES } from "@/utils/cryptojs";
import { escapeRegExp } from "lodash";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
interface FormState {
  groupNameDetail: dataSourceType;
  password: string;
  remember: boolean;
}

//专门验证用户名是否重复！
const checkCreatSiteForm = async (
  _rule: dataSourceType = {},
  value: any
) => {
  if (!value) {
    return Promise.reject(`${_rule.msg1}`);
  } else {
    var params = Object.assign({
      name: value,
    })
    if (detailData.id) {
      params.id = detailData.id
    }
    if (_rule.api) {
      let res = await request[`${_rule.api}`](params);
      if (!res) {
        return Promise.reject(`${_rule.msg2}`);
      } else {
        return Promise.resolve();
      }
    }
  }
};

//data
const btnPerm = ref<any[]>([]);
const statusOptions = [{ value: '全部' }, { value: '禁用' }, { value: '启用' }]
const memberFormState = ref<dataSourceType[]>([]);
let detailData = reactive<dataSourceType>({});
const statusType = ref<string | number>('全部')
const statusValue = ref<string | number>('')
const { query } = useRoute();
const instanceItems = ref<dataSourceType[]>([]);
const groupId = ref<any>('')
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true;  // 是否需要分页器中的自定义全选和删除

//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let configData1 = reactive<configDataType>({ total: 0, size: 10, records: [] });
const hotBaseTables = ref<any>(null);
const addNewTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
let moveRowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
let groupName = ref<any>()

// 模态框数据
const isAdd = ref<boolean>(false); //判断是新家、编辑或者批量上传来复用模态框
const isMove = ref<boolean>(false); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
let datas = reactive<any>({})
const isVisibleDetail = ref<boolean>(false);
const member_REF = ref();
const moveValue = ref<string | null>();
const moveOptions = ref<dataSourceType[]>([]);
const moveIds = ref<string | number[]>([]);
const groupNameDetail = ref<string>('');
const modAlProps: modeProp = reactive({
  width: "L",
  title: "添加",
});
// 模态框分页器
const pageNumber_modal = ref(0)
const pageSize_modal = ref(0)
// 组成员状态判断
const isPrevent = ref<Boolean>(true);
// 移动会员
const memberList = ref<any[]>([])

const onSearch = async () => { //搜索获取数据参数配置
  datas = {
    groupNameDetail: groupNameDetail.value
  }
  getRecord();
}

const switchChange = (record: any) => {
  let params: dataSourceType = {
    ids: [record.id],
  };
  request[!record.isEnabled ? 'fetchMemberDisable' : 'fetchMemberEnable'](params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRecord()
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

const statusChange = () => {//模型范围
  statusValue.value = statusType.value === '启用' ? '1' : statusType.value === '禁用' ? '0' : '';
  getRecord();
}

// 模板文件上传配置
const props_upload = reactive<dataSourceType>({
  action: '',
  accept: 'xlsx,xls',
  directory: false,
  listType: 'text'
})

const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改

// computed
rowSelection = computed(() => {
  return hotBaseTables.value.selectedRowKeys
})

moveRowSelection = computed(() => {
  return addNewTables.value.selectedRowKeys
})

//methods
const addRecord = async () => {//添加会员数据
  moveValue.value = '全部';
  isVisible.value = true;
  isAdd.value = true;
  isMove.value = false
  modAlProps.title = "添加新会员";
  modAlProps.width = "L";
  buttons.value = [
    {
      text: "确定",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  moveOptions.value.map((item: any) => {
    if (query.id == item.id) {
      item.disabled = true
    }
  })
  getModelRecord()
};
// 弹窗关闭时清空已选会员
watch(() => isVisible.value, (newVal, oldVal) => {
  if (newVal === false) {
    memberList.value = []
  }
})

const showDetail = async (item: dataSourceType) => {//编辑会员数据
  if(!btnPerm.value.includes('detailAble')) return
  const detailDataRes = await request.fetchMemberDetail({ id: item.id })
  memberFormState.value.length && memberFormState.value.forEach((item: dataSourceType) => {
    detailDataRes.instance?.instanceItems && detailDataRes.instance.instanceItems.length && detailDataRes.instance.instanceItems.forEach((dItem: dataSourceType) => {
      if (item.param === 'password' && item.param === dItem.field) {
        item.value = decrypt3DES(dItem.value)
      } else if (item.param === dItem.field && item.param !== 'password') {
        item.value = dItem.value
      }
      item.disabled = true
    })
    // if (item.param == 'memberStatus') {// 会员状态开启情况，是否禁用
    //   item.disabled = isPrevent.value;
    // }
  })
  detailData = detailDataRes

  isAdd.value = false;
  isMove.value = false
  isVisible.value = false
  isVisibleDetail.value = true;
  modAlProps.title = "会员详情";
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];

};

// 新添或编辑会员分组调取接口
const buttonMessage = async (msg: dataSourceType) => {

  let params1: dataSourceType = {
    groupId: isAdd.value ? query.id : groupId.value,
    ids: isAdd.value ? moveRowSelection.value : moveIds.value,
  };
  let params2: dataSourceType = {
    id: detailData.id,
    instance: {
      instanceItems: instanceItems.value,
      modelId: detailData?.instance?.modelId
    }
  };
  if (isVisibleDetail.value) {
    member_REF.value.validate().then(() => {
      request.fetchMemberUpdate(params2).then((res: any) => {
        if (res.code == "00000 00000") {
          getRecord();
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
    })
  } else if (isMove.value) {
    request.fetchChangeGroup(params1)
      .then((res: any) => {
        if (res.code == "00000 00000") {
          getRecord();
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  } else if (isAdd.value) {
    request.fetchChangeGroup(params1)
      .then((res: any) => {
        if (res.code == "00000 00000") {
          getRecord();
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  }

  isVisibleDetail.value = false;
  isVisible.value = false;
  isMove.value = false
  isAdd.value = false
};
// 删除单个会员
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value)
};
//删除已选所有会员
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm(Object.assign({}, msgModal.confirm, {
    title: '是否将所选的会员从其分组中移除？',
    content: '会员移除后将被移动到默认分组',
    icon: createVNode("i", { class: "iconfont icon-warn warning_ICON", style: { 'font-size': '20px', 'color': '#FAAD14FF', 'position': 'absolute', 'top': '-4px' } }),
    okText: '确定',
    onOk: async () => {
      await deleteRecords(keys)
      Modal.destroyAll();
    },
    onCancel() {
      Modal.destroyAll();
    },
  },))

}
const deleteRecords = async (keys: (string | number)[] = []) => { // 调接口删除会员
  await request.fetchRemoveGroup({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      getRecord()
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
}

//移动会员分组
const moveMember = async (record: any) => {
  if(!btnPerm.value.includes('moveAble')) return
  let list = []
  moveOptions.value.map((item: any) => {
    if (record.groupId === item.id) {
      item.disabled = true
    }
  })
  moveIds.value = record === 'allmove' ? rowSelection.value : [record.id]
  // console.log(moveIds.value);
  for (let i = 0; i < moveIds.value.length; i++) {
    list.push(moveIds.value[i])
  }
  memberList.value = list
  configData.records.forEach(item => {
    for (let i = 0; i < memberList.value.length; i++) {
      if (item.id === memberList.value[i]) {
        memberList.value[i] = item.userName

      }
    }
  })

  isVisible.value = true;
  isMove.value = true;
  isAdd.value = false;
  modAlProps.title = "移动会员";
  buttons.value = [
    {
      text: "确定",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
}

//筛选分组
const selectGroup = (e: any, options: dataSourceType) => {
  groupId.value = options.id
  getModelRecord()
}

const selectMove = (e: any, options: dataSourceType) => {
  groupId.value = options.id
}

const getModelRecord = async () => {
  const data: {} = {
    pageNumber: pageNumber_modal.value || 0,
    pageSize: pageSize_modal.value || 10,
    pageSort: '',
    groupId: groupId.value || null,
    id: datas.id || 0,
    keyWord: datas.groupNameDetail || '',
    nickName: datas.nickName || '',
    queryDto: datas.queryDto || '',
    status: statusValue.value || '',
  };
  const groupData = (await request.fetchMemberPage(data)) || {};
  let reqData = groupData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      createTime: item.createTime,
      groupId: item.groupId,
      groupName: item.groupName,
      isEnabled: item.isEnabled,
      lastLoginTime: item.lastLoginTime,
      nickName: item.nickName,
      userName: item.userName,
      userPhone: item.userPhone,
      id: item.id,
      oparation: ["详情", "移除", "移动"],
    };
    records.push(sourceData);
  });
  configData1.total = reqData.total;
  configData1.size = reqData.size;
  configData1.records = records;
};
const getRecord = async () => { // 获取会员表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
    pageSort: '',
    groupId: query.id || 0,
    id: datas.id || 0,
    keyWord: datas.groupNameDetail || '',
    nickName: datas.nickName || '',
    queryDto: datas.queryDto || '',
    status: statusValue.value || '',
  };
  const groupData = (await request.fetchMemberPage(data)) || {};
  let reqData = groupData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      createTime: item.createTime,
      groupId: item.groupId,
      userName: item.userName,
      groupName: item.groupName,
      isEnabled: item.isEnabled,
      lastLoginTime: item.lastLoginTime,
      nickName: item.nickName,
      userPhone: item.userPhone,
      id: item.id,
      oparation: ["详情", "移除", "移动"],
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  nextTick(() => {
    scroll.y = getTableScroll(74, "groupNameDetail").y;
    scroll.isFixed = getTableScroll(74, "groupNameDetail").isFixed;
  })
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize
  }
  getRecord();
}

//
const changePage_motal = (data: { pageCurrent: any; pageSize: any }) => {
  pageNumber_modal.value = data.pageCurrent;
  pageSize_modal.value = data.pageSize;
  getModelRecord()
}
const getGroup = async () => {
  let list = await request.fetchMemberGroupList()
  moveOptions.value = [...list]
  moveOptions.value.map((item: any) =>
    item.value = item.name
  )
}

//获取详情
const getDetail = async () => {
  const data = await request.fetchModelMemberModel()
  memberFormState.value = JSON.parse(data.enableJson);
  memberFormState.value.forEach((item: dataSourceType) => {
    if (item.componentName == 'userName') {
      item.rule.validator = checkCreatSiteForm;
    } else {
      if (item.rule.validator) {
        item.rule.validator = new Function(
          "return " + item.rule.validator
        )();
      }
    }

  });
}
// 检测是否开启密级管理
const isOpenPrevent = async () => {
  isPrevent.value = await request.isOpenPrevent();
}

//watch
watch(() => memberFormState.value, (newVal, oldVal) => {
  instanceItems.value = []
  newVal.length && newVal.forEach((item: dataSourceType) => {
    let obj: dataSourceType = {}
    if (item.param === 'password') {
      obj.field = item.param;
      obj.value = encrypt3DES(item.value)
    } else {
      obj.field = item.param;
      obj.value = item.value || '';
    }
    instanceItems.value.push(obj)
  })
}, { deep: true })

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  groupName.value = query.groupName
  getRecord();
  getDetail();
  getGroup();
  isOpenPrevent();
});
</script>
<style lang="scss" scoped>
.groupNameDetail {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;



  .groupNameDetail_button {
    padding-bottom: 24px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .statusSelect {
      margin-left: auto;
    }

    .searchContent {
      margin-right: 0px;
      margin-left: 16px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  ::v-deep(.ant-table-tbody > tr > td:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords1 {
    margin-left: 16px;
  }
}


.add-item {
  .header-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 24px;

    ::v-deep(.group-select .ant-select) {
      width: 288px;
    }

    .searchContent {
      margin-left: 16px;
      width: 192px;
      height: 32px;

      ::v-deep(.ant-input-affix-wrapper) {
        height: 32px;
      }
    }
  }
}

.move-item {
  display: flex;
  flex-direction: column;

  span {
    margin-bottom: 8px;
  }
}

.baseTable {
  position: relative;
}

.baseTable .aTable {
  max-height: 450px;
  height: fit-content;
  overflow: auto;
}

:deep(.ant-form-item) {
  width: 604px;
  display: flex;


  .ant-form-item-control {
    width: 508px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 80px;
    text-align: right;
  }
}

::v-deep(.statusSelect .ant-select) {
  width: 112px;
}

::v-deep(.move-item .ant-select) {
  width: 492px;
}

::v-deep(.anticon.ant-input-clear-icon-has-suffix) {
  margin-right: 20px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
<style lang="less">
.member_detail_modal {
  .ant-modal-body::after {
    position: absolute;
    width: 100%;
    height: calc(100% - 130px);
    background: transparent;
    content: '';
    top: 65px;
    left: 0;
    z-index: 100;
  }

  .basic-item:nth-last-of-type(1) {
    margin-bottom: -24px;
  }
}

.memberList {
  display: flex;
}

.groupName {
  font-weight: 700;
  margin-bottom: 15px;
}

::v-deep(.ant-table-body) {
  height: 500px;
}
</style>